﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Sodu.Util.HttpHelper
{

    public delegate void HandleResult(string result);
    public class HttpHelper
    {

        public static CookieContainer CurrBaseCookie
        {
            get
            {
                return SoduConstants.SoduContantsValue.SoduGlobleCookie;
            }
            set
            {
                SoduConstants.SoduContantsValue.SoduGlobleCookie = value;
            }
        }

        public static HandleResult Handle;

        /// <summary>
        /// postdata
        /// </summary>
        public static string PostData = string.Empty;

        /// <summary>
        /// 公共的webrequest
        /// </summary>
        public static HttpWebRequest webRequest;
        public static void HttpGetRequest(string Url, HandleResult handle)
        {
            Handle = handle;
            webRequest = (HttpWebRequest)WebRequest.Create(Url);
            webRequest.Method = "Get";
            webRequest.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.Now.ToString();
            webRequest.CookieContainer = CurrBaseCookie;

            webRequest.BeginGetResponse(new AsyncCallback(GetHandleResponse), webRequest);
        }
        public static void GetHandleResponse(IAsyncResult asyncResult)
        {
            HttpWebRequest httpRequest = null;
            HttpWebResponse httpResponse = null;
            string result = string.Empty;
            try
            {
                httpRequest = (HttpWebRequest)asyncResult.AsyncState;
                httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(asyncResult);

                using (var reader = new StreamReader(httpResponse.GetResponseStream(), new HtmlAgilityPack.Gb2312Encoding()))
                {
                    result = reader.ReadToEnd();
                    reader.Dispose();
                }
            }
            catch
            {
                result = "";
            }
            finally
            {
                if (httpRequest != null) httpRequest.Abort();
                if (httpResponse != null) httpResponse.Dispose();
            }
            Handle(result);
        }

        public static void HttpPostRequest(string Url, HandleResult handle, string postData)
        {
            Handle = handle;
            PostData = postData;

            webRequest = (HttpWebRequest)WebRequest.Create(Url);
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight-2-b1, */*";
            webRequest.Headers["Pragma"] = "no-cache";
            webRequest.Headers["Cache-Control"] = "no-cache";

            webRequest.CookieContainer = CurrBaseCookie;
            webRequest.BeginGetRequestStream(requestCallback, webRequest);
        }

        private static void requestCallback(IAsyncResult result)
        {
            try
            {
                //获取异步操作返回的的信息
                HttpWebRequest request = (HttpWebRequest)result.AsyncState;
                //结束对 Internet 资源的异步请求
                using (Stream postStream = request.EndGetRequestStream(result))
                {
                    byte[] data = Encoding.UTF8.GetBytes(PostData);
                    postStream.Write(data, 0, data.Length);
                }

                //返回应答请求异步操作的状态
                request.BeginGetResponse(PostHandleResponse, request);
            }
            catch (WebException e)
            {
                Handle("");
                return;
            }

        }
        public static void PostHandleResponse(IAsyncResult asyncResult)
        {
            HttpWebRequest httpRequest = null;
            HttpWebResponse httpResponse = null;
            string result = string.Empty;
            try
            {
                httpRequest = (HttpWebRequest)asyncResult.AsyncState;
                httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(asyncResult);

                using (var reader = new StreamReader(httpResponse.GetResponseStream(), new HtmlAgilityPack.Gb2312Encoding()))
                {
                    result = reader.ReadToEnd();
                    reader.Dispose();
                }
            }
            catch
            {
                result = "";
            }
            finally
            {
                if (httpRequest != null) httpRequest.Abort();
                if (httpResponse != null) httpResponse.Dispose();
            }
            Handle(result);
        }


        //private async void SendNetworkRequest(Action networkRequest)
        //{
        //    AutoResetEvent autoResetevent = new AutoResetEvent(false);
        //    await Task.Factory.StartNew(networkRequest);

        //    autoResetevent.WaitOne(3000);
        //    if (webRequest != null)
        //    {
        //        try
        //        {
        //            webRequest.Abort();
        //        }
        //        catch (Exception ex)
        //        {

        //        }
        //    }
        //}
    }

}
